﻿using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;

namespace CCU.Core.Channel
{
    public class ContextAttachingMessageInspector : IClientMessageInspector
    {
        public void AfterReceiveReply(ref Message reply, object correlationState)
        {
            if (reply.Headers.FindHeader(CCUChannelExtra.callContextKey, CCUChannelExtra.contextHeaderNamespace) < 0)
            {
                return;
            }
            CCUChannelExtra context = reply.Headers.GetHeader<CCUChannelExtra>(CCUChannelExtra.callContextKey, CCUChannelExtra.contextHeaderNamespace);
            if (context == null)
            {
                return;
            }
            CCUChannelExtra.GetEntity = context;
        }

        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            MessageHeader<CCUChannelExtra> contextHeader = new MessageHeader<CCUChannelExtra>(CCUChannelExtra.GetEntity);
            request.Headers.Add(contextHeader.GetUntypedHeader(CCUChannelExtra.callContextKey, CCUChannelExtra.contextHeaderNamespace));
            return null;
        }
    }
}
